//
//  QCUserProtocolViewController.m
//  QCAppProject
//
//  Created by jiale yang on 2021/8/21.
//

#import "QCUserProtocolViewController.h"
#import <WebKit/WebKit.h>

@interface QCUserProtocolViewController ()<WKNavigationDelegate>

@property(nonatomic,strong)WKWebView*wkWebView;
@property(nonatomic,strong)UIProgressView*progressView;

@end

@implementation QCUserProtocolViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.isProtocolJump) {
        self.isProtocolJump();
    }
}

- (void)initUI {
    self.isShowBackButton = YES;
    self.title = @"用户协议";
    self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    self.wkWebView.frame=CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT - kTopBarHeight);
    self.wkWebView.navigationDelegate=self;
    [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"用户协议.docx" withExtension:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
    [self.wkWebView loadRequest:request];
    [self.view addSubview:self.wkWebView];
    [self.view addSubview:self.progressView];
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ( [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.progressView.alpha = 1.0f;
        [self.progressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 self.progressView.alpha = 0.0f;
                             }
                             completion:^(BOOL finished) {
                                 [self.progressView setProgress:0 animated:NO];
                             }];
        }
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
    }
    return _progressView;
}

- (void)dealloc {//最后别忘了销毁KVO监听
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
    [self.wkWebView removeFromSuperview];
    self.wkWebView=nil;
    self.wkWebView.navigationDelegate=nil;
    
}
@end
